package cn.daichi.elasticsearchdemo.service.impl;

import cn.daichi.elasticsearchdemo.entity.Post;
import cn.daichi.elasticsearchdemo.model.PostDocument;
import cn.daichi.elasticsearchdemo.repository.PostRepository;
import cn.daichi.elasticsearchdemo.service.PostService;
import cn.daichi.elasticsearchdemo.service.SearchService;
import cn.daichi.elasticsearchdemo.vo.PostVo;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private PostService postService;


    @Override
    public IPage search(Page page, String keyword) {

        Long current = page.getCurrent() - 1;
        Long size = page.getSize();
        Pageable pageable = PageRequest.of(current.intValue(), size.intValue());

        // 根据title和content两个字段查询
        org.springframework.data.domain.Page<PostDocument> documents = postRepository.findByTitleOrContent(keyword, keyword, pageable);

        Page pageData = new Page(page.getCurrent(), page.getSize(), documents.getTotalElements());
        pageData.setRecords(documents.getContent());

        return pageData;
    }

    @Override
    public int initEsData() {

        long count = postService.count();
        Page<PostVo> page = new Page<>();
        page.setSize(count);
        IPage<PostVo> postPage = postService.paging(page, null, null, null, null, null);

        List<PostVo> records = postPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return 0;
        }

        List<PostDocument> documents = new ArrayList<>();
        for (PostVo postVo : records) {
            PostDocument document = new PostDocument();
            BeanUtils.copyProperties(postVo, document);
            documents.add(document);
        }

        postRepository.saveAll(documents);

        return documents.size();

    }

    @Override
    public void createOrUpdateIndex(Long postId) {

        PostVo postVo = postService.selectOnePost(new QueryWrapper<Post>().eq("p.id", postId));
        PostDocument postDocument = new PostDocument();
        BeanUtils.copyProperties(postVo, postDocument);

        postRepository.save(postDocument);

        log.info("es索引更新成功！ -----> {}", postDocument);
    }

    @Override
    public void removeIndex(Long postId) {
        postRepository.deleteById(postId);
        log.info("es索引删除成功！ -----> {}", postId);
    }
}
